/*****************************************************************************
 * Product: 数据同步解决方案                                                    
 * Copyright (C) 2010-2011  瑞科软件. All Rights Reserved.                                                                       *
 * 改程序是开源的，您可以修改源代码，做二次开发，定制您自己的同步程序                     
 * 您可以通过我们的网站了解详细信息，包括安装与使用指南，  http://www.ruike.org         
 * 																		      			
 *****************************************************************************/
package com.mk.code.engine.mean.method;

import java.util.ArrayList;
import java.util.List;

import com.mk.SQLTree;
import com.mk.code.config.ParseFactory;

/**
 * 
 * @功能 所有的语法解析都是基于顺序的解析方式，即从左到右的读取顺序
 * @author 张华
 * @date Jul 24, 2009
 * @version 1.0 Jul 24, 2009 9:58:15 PM
 */
public class SequenceMethod extends AbstractMethod {

	private String[] words;

	public List<AbstractMethod> sequence = new ArrayList<AbstractMethod>();

	public SequenceMethod(String mean) {
		SQLTree aSQLTree = new SQLTree(mean);
		words = aSQLTree.parse();

	}

	public SequenceMethod(AbstractMethod parent) {
		super(parent);
	}

	public String[] getValue() {
		return words;
	}

	public void parse() {
		while (offsetIndex < words.length) {
			parseSub();
		}

	}

	public void parseSub() {
		if (offsetIndex == words.length) {
			return;
		}

		String meanWord = words[offsetIndex];
		String meanValue = (String) ParseFactory.aMap.get(meanWord);
		AbstractMethod abstractMethod = null;
		int len = meanValue==null?0:meanValue.length();
		if (meanValue == null) {
			abstractMethod = new SingleWordMethod(this);
		} else if (meanWord.equals("[")) {
			abstractMethod = new OptionMethod(this);
		} else if (len>2&&meanValue.substring(0, 1).equals("/")&&meanValue.substring(len-1, len).equals("/")) {
			abstractMethod = new RegixMethod(this);
			((RegixMethod)abstractMethod).setName(meanValue);
		} else {
			abstractMethod = ParseFactory.getInstance(meanValue);
			sequence.add(abstractMethod);
			offsetIndex += meanWord.length();
			return;
		}
		abstractMethod.index = offsetIndex;
		abstractMethod.offsetIndex = 0;
		abstractMethod.parse();
		sequence.add(abstractMethod);
	}

	/**
	 * 值的解析, 每次解析成功都要返回true,并且加偏移量
	 */
	public boolean process(String args) {
		boolean flag = true;
		for (AbstractMethod aAbstractMethod : sequence) {
			flag = aAbstractMethod.process("");
			if (!flag) {
				return false;
			}
		}
		return true;
	}

}
